var app = getApp();
import {
  api,
  util
} from '../../../js/util';
import {
  router
} from '../../../js/router';
import {
  list
} from '../../../js/modules/mall';
import authorize from '../../../js/modules/authorize';
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      // 在组件实例进入页面节点树时执行
      
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {
      //this.get_category_screens();
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    enableZeroStockBuy: {
      type: Boolean,
      value: false
    },
    isShowZeroStock: {
      type: Number,
      value: 0
    },
    priceRange: {
      type: Array,
      value: []
    },
    typeId: {
      type: Number,
      value: 0,
      observer(newValue) {
        // if (newValue != this.data.odd_type_id) {
        //   this.get_category_screens();
        // }
        // this.data.odd_type_id = newValue;

      }
    },
    bid: {
      type: String,
      value: "",
      observer(newValue) {
        // if (newValue != this.data.odd_bid) {
        //   this.get_category_screens();
        // }
        // this.data.odd_bid = newValue;
      }
    },
    vid: {
      type: String,
      value: "",
      observer(newValue) {
        // if (newValue != this.data.odd_bid) {
        //   this.get_category_screens();
        // }
        // this.data.odd_bid = newValue;
      }
    },
    cid:{
      type: Number,
      value: 0,
      observer(newValue) {
        if (newValue != this.data.odd_cid) {
          this.setData({
            keyword:""
          })
        }
        this.data.odd_cid = newValue;

      }
    },
    minprice: {
      type: String,
      value: ""
    },
    extattrs: {
      type: String,
      value: ""
    },
    customAttrs: {
      type: String,
      value: ""
    },
    adjustBottom:{
      type:Boolean,
      value:false
    },
    mainColor:String,
    isIphoneX:Boolean,    
    ShowVendorName:Boolean,
    NotShowProductNoneOffered: { // 不显示无货商品
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    brandList: [],
    vendorList:[],
    keyword: "",
    keywordVendor:"",
    isOpen: '',
    open: '',
    attrsList: [],
    attrItem:[],
    brandIds: '',
    screenData: {},
    open_dic: {},
    odd_cid: 0,
    odd_type_id:0,
    odd_bid: 0,
    pre_isShowZeroStock:0,
    tagsList:[],//标签
    minToPrice:'',//最小值
    maxPrice:'',//最大值
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**搜索供货商的关键字 */
    keywordVendorInput(e) {
      this.setData({
        keywordVendor: (e.detail.value).toLowerCase()
      });
      this.searchVendor();
    },
    /**搜索品牌的关键字 */
    keywordInput(e) {
      this.setData({
        keyword: (e.detail.value).toLowerCase()
      });
      this.searchBrand();
    },
    /**加载品牌 */
    get_category_screens() {
      var that = this;
      let { keyword,keywordVendor, typeId}=this.data;
      typeId = app.globalData.product_list.typeId?app.globalData.product_list.typeId:typeId;
      var param = {
        keyword: keyword,
        keywordVendor:keywordVendor,
        typeId: typeId
      };
      var selectVendor = that.data.vid || "";
      var selectBrand = that.data.bid || "";
      var minprice = that.data.minprice || "";
      var extattrs = that.data.extattrs || "";
      var isShowZeroStock = that.data.isShowZeroStock || 0;
      that.data.pre_isShowZeroStock = isShowZeroStock;
      that.data.priceRange = that.data.priceRange;
      if (minprice.length > 0) {
        for (var i in that.data.priceRange) {
          if (minprice.indexOf(`${that.data.priceRange[i].MinPrice},${that.data.priceRange[i].MaxPrice}`) > -1) {
            that.data.priceRange[i].IsSelected = true;
          } else {
            that.data.priceRange[i].IsSelected = false;
          }
        }
      }

      list.get_category_screens(param, function(res) {
        for (var index in res.vendors) {
          if (selectVendor.indexOf(res.vendors[index].Id) > -1) {
            res.vendors[index].IsSelected = true;
          }
        }

        for (var index in res.brands) {
          if (selectBrand.indexOf(res.brands[index].Id) > -1) {
            res.brands[index].IsSelected = true;
          }
        }
        for (var index in res.tags) {
          if (selectBrand.indexOf(res.tags[index].Id) > -1) {
            res.tags[index].IsSelected = true;
          }
        }
        var attrs = [];
        var items = [];
        for (var i in res.attrs) {
          var attr_item = res.attrs[i];
          if(attr_item.AttrType==1){
            attr_item.IsRequired=0;
            attr_item.FieldName = attr_item.AttrName;
            attr_item.Placeholder = '';
            attr_item.value = '';
            items.push(attr_item)
          }else{
            //属性选框类型
            var arr_type = attr_item.AttrName.split("┊");
            attr_item.Name = arr_type[0];
            attr_item.Type = arr_type[1];
            //选择项
            var arr = attr_item.Candidate.split(",");
            attr_item.Candidates = attr_item.Candidates || [];
            for (var j in arr) {
              attr_item.Candidates.push({
                IsSelected: extattrs.indexOf(`${attr_item.Id}|${arr[j]}|${attr_item.Name}`) > -1,
                Name: arr[j]
              });
            }
            attrs.push(attr_item)
          }
        }
        console.log('attrsList==', attrs)
        that.setData({
          brandList: res.brands,
          vendorList:res.vendors,
          tagsList:res.tags,
          attrsList: attrs,
          attrItem: items,
          priceRange: that.data.priceRange
        });
      });
    },
    inputCallBack(e){
      let id = e.currentTarget.dataset.id
      e.detail.dataId = id
      this.dealCustomInfosList(e)
    },
    // 处理自定义订单输入的公用方法
    dealCustomInfosList(event) {
      let value = event.detail;
      if(!value) {
        wx.showToast({
          title: '数据格式错误',
          icon: 'none'
        })
        return
      }
      let customInfosList = this.data.attrItem
      let flag = false
      if(customInfosList.length <= 0) {
        customInfosList.push(value)
        return
      }
      for(var i = 0; i < customInfosList.length; i++) {
        if(customInfosList[i].Id === value.dataId) {
          customInfosList[i].value = value.value
          flag = true
          break
        }
      }
      if(!flag) {
        customInfosList.push(value)
      }
      this.setData({
        attrItem: customInfosList
      })
    },
    /**选择品牌 */
    onSelectBrandEvent(e) {
      var that = this;
      var o = e.currentTarget.dataset;
      var brandList = this.data.brandList;
      var brand = brandList[o.idx];
      brand.IsSelected = !brand.IsSelected;

      this.setData({
        brandList: brandList
      });
    },
    /**选择供货商 */
    onSelectVendorEvent(e) {
      var that = this;
      var o = e.currentTarget.dataset;
      var vendorList = this.data.vendorList;
      if (vendorList && vendorList.length > 0) {
        var vendor = vendorList[o.idx];
        vendor.IsSelected = !vendor.IsSelected;
      }
      this.setData({
        vendorList: vendorList
      });
    },
    /**选择商品标签 */
    onSelectTagsEvent(e){
      var that = this;
      var o = e.currentTarget.dataset;
      var tagsList = this.data.tagsList;
      var brand = tagsList[o.idx];
      brand.IsSelected = !brand.IsSelected;
      this.setData({
        tagsList: tagsList
      });
    },
    /**选择属性事件 */
    onSelectAttrEvent(e) {
      var that = this;
      var o = e.currentTarget.dataset;
      var pindex = o.pindex,
        cindex = o.cindex,
        t = o.type;
      var attr_item = that.data.attrsList[pindex];
      if (attr_item == undefined) return;
      for (var j in attr_item.Candidates) {
        if (j == cindex) {
          attr_item.Candidates[j].IsSelected = !attr_item.Candidates[j].IsSelected;
        } else {
          if (t == 0) {
            attr_item.Candidates[j].IsSelected = false;
          }
        }
      }
      that.setData({
        attrsList: that.data.attrsList
      });
    },
    /**选择价格事件 */
    onSelectPriceEvent(e) {
      var that = this;
      var o = e.currentTarget.dataset;
      var index = o.index;
      var attr_item = that.data.priceRange;
      if (attr_item == undefined) return;
      for (var j in attr_item) {
        if (j == index) {
          attr_item[j].IsSelected = !attr_item[j].IsSelected;
        } else {
          attr_item[j].IsSelected = false;
        }
      }
      that.setData({
        priceRange: attr_item
      });
    },
    //重置
    reset() {
      var that = this;
      var brandList = this.data.brandList;
      if (brandList && brandList.length > 0) {
        for (var i = 0; i < brandList.length; i++) {
          var brand = brandList[i];
          brand.IsSelected = false;
        }
      }
      var vendorList = this.data.vendorList;
      if (vendorList && vendorList.length > 0) {
        for (var i = 0; i < vendorList.length; i++) {
          var vendor = vendorList[i];
          vendor.IsSelected = false;
        }
      }
      var tagsList = that.data.tagsList;
      if (tagsList && tagsList.length > 0) {
        for(var i = 0;i<tagsList.length;i++){
          var tag = tagsList[i];
          tag.IsSelected = false;
        }
      }
      var priceRange = that.data.priceRange;
      if (priceRange && priceRange.length > 0) {
        for (var j in priceRange) {
          priceRange[j].IsSelected = false;
        }
      }
      var attrsList = that.data.attrsList;
      if (attrsList && attrsList.length > 0) {
        for (var i in attrsList) {
          var attr_item = attrsList[i];
          for (var j in attr_item.Candidates) {
            attr_item.Candidates[j].IsSelected = false;
          }
        }
      }
      var items = that.data.attrItem;
      if (items && items.length > 0) {
        for (var i in items) {
          items[i].value = '';
        }
      }
      this.setData({
        tagsList:tagsList,
        brandList:brandList,
        vendorList:vendorList,
        selectedCategoryId: 0,
        priceRange:priceRange,
        attrsList:attrsList,
        attrItem:items,
        isShowZeroStock: that.data.pre_isShowZeroStock,
        minToPrice:'',
        maxPrice:'',
      });
    },
    /**确认，返回商品列表 */
    confirm() {
      var that = this;
       //组装所有选中的供货商
       var vArry = [];
       var vendorList = this.data.vendorList;
       if (vendorList && vendorList.length > 0) {
        for (var i = 0; i < vendorList.length; i++) {
          var v = vendorList[i];
          if (v.IsSelected) {
            vArry.push(v.Id);
          }
        }
        }
       var vids = "";
       if (vArry.length > 0) {
         vids = vArry.join(',');
       }
      //组装所有选中的品牌
      var bArry = [];
      var brandList = this.data.brandList;
      if (brandList && brandList.length > 0) {
        for (var i = 0; i < brandList.length; i++) {
          var b = brandList[i];
          if (b.IsSelected) {
            bArry.push(b.Id);
          }
        }
      }
      var bids = "";
      if (bArry.length > 0) {
        bids = bArry.join(',');
      }
      //组装所有选中的商品标签
      var tagArry = [];
      var tagsList = this.data.tagsList;
      if (tagsList && tagsList.length > 0) {
        for (var i = 0; i < tagsList.length; i++) {
          var b = tagsList[i];
          if (b.IsSelected) {
            tagArry.push(b.Id);
          }
        }
      }
      var tags = "";
      if (tagArry.length > 0) {
        tags = tagArry.join(',');
      }
      //价格区间
      var minprice = "";
      var priceRange = this.data.priceRange;
      if (priceRange && priceRange.length > 0) {
        for (var j in priceRange) {
          if (priceRange[j].IsSelected) {
            minprice = priceRange[j].MinPrice + "," + priceRange[j].MaxPrice;
          }
        }
      }
      var extattrs = [];
      //其它选择项
      var attrsList = this.data.attrsList;
      if (attrsList && attrsList.length > 0) {
        for (var i in attrsList) {
          var attr_item = attrsList[i];
          for (var j in attr_item.Candidates) {
            if (attr_item.Candidates[j].IsSelected) {
              extattrs.push(`${attr_item.Id}|${attr_item.Candidates[j].Name}|${attr_item.Name}`);
            }
          }
        }
      }
      var customAttrs = '';
      var items = that.data.attrItem;
      if (items && items.length > 0) {
        for (var i in items) {
          var item = items[i];
            if (item.value) {
              customAttrs += `<attr_${item.Id}><![CDATA[${item.value}]]></attr_${item.Id}>`;
              // customAttrs.push(`<attr_${item.Id}><![CDATA[${item.value}]]><attr_${item.Id}>`);
            }
        }
      }
      let isShowZeroStock = this.data.isShowZeroStock
      let NotShowProductNoneOffered = this.data.NotShowProductNoneOffered
      if (NotShowProductNoneOffered) {
        isShowZeroStock = 0
      }
      this.triggerEvent("onFilterComfirmEvent", {
        vid:vids,
        tag:tags,
        bid: bids,
        extattrs: extattrs.join(","),
        customAttrs: customAttrs,
        isShowZeroStock: isShowZeroStock,
        minprice: minprice,
        minToPrice: that.data.minToPrice,
        maxPrice: that.data.maxPrice
      });
    },
    /**搜索品牌 */
    searchVendor() {
      var vendorList = this.data.vendorList;
      var key = this.data.keywordVendor;
      if (vendorList && vendorList.length > 0) {
        for (var i = 0; i < vendorList.length; i++) {
          var vendor = vendorList[i];
          var vname = vendor.Name.toLowerCase();
          if (vname.indexOf(key) == -1) {
            vendor.hidden = 'none';
          } else {
            vendor.hidden = '';
          }
        }
        this.setData({
          vendorList: vendorList
        });
      }
    },
    /**搜索品牌 */
    searchBrand() {
      var brandList = this.data.brandList;
      var key = this.data.keyword;
      if (brandList && brandList.length > 0) {
        for (var i = 0; i < brandList.length; i++) {
          var brand = brandList[i];
          var bname = brand.Name.toLowerCase();
          if (bname.indexOf(key) == -1) {
            brand.hidden = 'none';
          } else {
            brand.hidden = '';
          }
        }
        this.setData({
          brandList: brandList
        });
      }
    },
    /**
     * 品牌展开切换
     */
    arrowSwitch: function(e) {
      var type = e.currentTarget.dataset.type;
      var _open = '',
        obj = null,
        index = 0;
      if (this.data.open_dic[type]) {
        obj = this.data.open_dic[type];
      }
      if (obj && obj.open == 'open') {
        obj.open = '';
        obj.isOpen = '';
      } else {
        obj = obj || {
          isOpen: '',
          open: ''
        };
        obj.open = "open";
        obj.isOpen = 'open';
      };
      this.data.open_dic[type] = obj;
      this.setData({
        open_dic: this.data.open_dic
      });
    },
    /**选择是否显示无货商品 */
    selectZeroStock() {
      var isShowZeroStock = this.data.isShowZeroStock;
      this.setData({
        isShowZeroStock: isShowZeroStock == 1 ? 0 : 1
      });
    },
    //价格--最小价格
    bindMinprice(e){
      let value = e.detail.value
      value = parseFloat(value)
      if (isNaN(value)) {
        value = ''
      }
      this.setData({
        minToPrice: value
      })
    },
    bindMaxprice(e){
      let value = e.detail.value
      value = parseFloat(value)
      if (isNaN(value)) {
        value = ''
      }
      this.setData({
        maxPrice: value
      })
    },
  }
})